<template>
  <el-dialog
    v-model="formVisible"
    :title="title"
    :append-to-body="true"
    destroy-on-close
    width="700px"
    top="20vh"
    @close="closeDialog"
  >
    <el-form
      ref="taskFormRef"
      :model="scheduleTaskForm"
      :rules="rules"
      label-width="110px"
      ><el-tabs v-model="activeName" class="tabs">
        <el-tab-pane label="基础信息配置" name="first">
          <el-form-item label="任务类型" prop="jobType">
            <el-radio-group v-model="scheduleTaskForm.jobType" style="width: 80%">
              <el-radio :value="1">Http任务</el-radio>
              <el-radio :value="2">程序集任务</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="任务名称" prop="title">
            <el-input v-model="scheduleTaskForm.title" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="任务分组" prop="jobGroup">
            <el-input v-model="scheduleTaskForm.jobGroup" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="按周期运行" prop="runLoop">
            <el-switch style="width: 80%" v-model="scheduleTaskForm.runLoop"></el-switch>
            <span>如果关闭按钮表示只在任务开始时执行一次 </span>
          </el-form-item>
          <el-form-item
            prop="cronExpression"
            label="Cron表达式"
            v-show="scheduleTaskForm.runLoop == true"
          >
            <el-input
              v-model="scheduleTaskForm.cronExpression"
              style="width: 80%"
            ></el-input>
          </el-form-item>
          <el-form-item label="开始时间" prop="startDate">
            <el-date-picker
              v-model="scheduleTaskForm.startDate"
              type="datetime"
              style="width: 80%"
              placeholder="选择任务开始日期时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间" prop="endDate">
            <el-date-picker
              v-model="scheduleTaskForm.endDate"
              type="datetime"
              style="width: 80%"
              placeholder="选择任务结束日期时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            >
            </el-date-picker>
            <span>为空表示不限制任务的停止时间 </span>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              style="width: 80%"
              v-model="scheduleTaskForm.remark"
            ></el-input>
          </el-form-item>
          <el-form-item label="创建成功启动" prop="runNow">
            <el-switch style="width: 80%" v-model="scheduleTaskForm.runNow"></el-switch>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane
          label="元数据配置"
          name="second"
          v-if="scheduleTaskForm.jobType == 1"
        >
          <el-form-item prop="httpRequestUrl" label="请求地址">
            <el-input
              v-model="scheduleTaskForm.requestUrl"
              style="width: 80%"
            ></el-input>
          </el-form-item>
          <el-form-item label="请求方式" prop="method">
            <el-select
              style="width: 80%"
              v-model="scheduleTaskForm.method"
              placeholder="请选择请求方式"
            >
              <el-option label="POST" value="POST"></el-option>
              <el-option label="GET" value="GET"></el-option>
              <el-option label="PUT" value="PUT"></el-option>
              <el-option label="DELETE" value="DELETE"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="自定义请求头" prop="headers">
            <el-input
              type="textarea"
              style="width: 80%"
              v-model="scheduleTaskForm.headers"
              placeholder="请输入自定义请求头"
            ></el-input>
            <span
              >请确保请输入json字符串格式的内容正确
              如"[{Authorzation:11111}，{A:111}]后台会自动解析"</span
            >
          </el-form-item>
          <el-form-item label="数据格式" prop="contentType">
            <el-radio-group style="width: 80%" v-model="scheduleTaskForm.contentType">
              <el-radio value="form-data">form-data</el-radio>
              <el-radio value="json-data">json-data</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="数据内容" prop="body">
            <el-input
              style="width: 80%"
              type="textarea"
              v-model="scheduleTaskForm.body"
              placeholder="请输入数据内容"
            ></el-input>
            <span
              >请确保请输入json字符串格式的内容正确
              如"[{Authorzation:11111}，{A:111}]后台会自动解析"</span
            >
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane v-if="scheduleTaskForm.jobType == 2" label="元数据配置" name="third">
          <el-form-item prop="assemblyName" label="程序集名称">
            <el-input
              style="width: 80%"
              v-model="scheduleTaskForm.assemblyName"
            ></el-input>
          </el-form-item>
          <el-form-item prop="className" label="执行类名称">
            <el-input style="width: 80%" v-model="scheduleTaskForm.className"></el-input>
          </el-form-item>
          <el-form-item prop="methodName" label="执行方法名称">
            <el-input style="width: 80%" v-model="scheduleTaskForm.methodName"></el-input>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="异常报警通知" name="fourth">
          <el-form-item label="监护人" prop="keeperInfo">
            <el-select
              multiple
              style="width: 80%"
              v-model="scheduleTaskForm.keeperInfo"
              placeholder="请选择监护人"
            >
              <el-option
                v-for="item in userlist"
                :key="item.id"
                :label="item.userName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="通知方式" prop="noticetyes">
            <el-select
              style="width: 80%"
              multiple
              v-model="scheduleTaskForm.noticetyes"
              placeholder="请选择通知方式"
            >
              <el-option label="邮件" value="mail"></el-option>
              <el-option label="站内信" value="signalr"></el-option>
            </el-select>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="执行异常重试" name="fifth">
          <el-form-item label="是否重试" prop="isHaveRetry">
            <el-switch
              style="width: 80%"
              v-model="scheduleTaskForm.isHaveRetry"
            ></el-switch>
            <span
              >开启异常重试后在执行接口逻辑返回报错以后会进行重试，目前只支持Http任务调用</span
            >
          </el-form-item>
          <el-form-item
            label="最大重试次数"
            v-show="scheduleTaskForm.isHaveRetry"
            prop="maxRetryCount"
          >
            <el-input
              style="width: 80%"
              type="number"
              min="0"
              v-model="scheduleTaskForm.maxRetryCount"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="重试间隔时间"
            v-show="scheduleTaskForm.isHaveRetry"
            prop="retryInterval"
          >
            <el-input
              style="width: 80%"
              type="number"
              min="0"
              v-model="scheduleTaskForm.retryInterval"
            ></el-input>
            <span>重试时间间隔单位是秒</span>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <div class="modal-footer">
      <el-button @click="saveSchedule" :icon="Plus" type="primary">保存</el-button>
    </div>
  </el-dialog>
</template>
<script setup lang="ts">
import { FormInstance } from "element-plus";
import { addscheduletask } from "@/api/schedule/index";
import { getalluserlist } from "@/api/identity/user/index";
import moment from "moment";
import { Plus } from "@element-plus/icons-vue";
const props = defineProps({
  scheduleId: { type: String, default: null },
});
let formVisible = ref<boolean>(true);
let title = ref<string>("");
let isEdit = ref<boolean>(false);
let taskFormRef = ref<FormInstance>();
let userlist = ref<any>([]);
let scheduleTaskForm = ref<any>({
  jobType: 1,
  startDate: null,
  endDate: null,
  httpContentType: "form-data",
  keeperInfo: [],
});
let activeName = ref<string>("first");
let rules = ref<any>({
  title: [{ required: true, message: "请输入任务名称", trigger: "blur" }],
  jobGroup: [{ required: true, message: "请输入任务分组", trigger: "blur" }],
  startDate: [
    {
      required: true,
      message: "请选择日期时间",
      trigger: "change",
    },
  ],

  requestUrl: [{ required: true, message: "请输入请求地址", trigger: "blur" }],
  method: [{ required: true, message: "请选择请求方式", trigger: "change" }],
});
const emit = defineEmits(["close", "refresh"]);
const closeDialog = () => {
  formVisible.value = false;
  emit("close", formVisible.value);
};

const getUser = () => {
  getalluserlist().then((res: any) => {
    userlist.value = res;
  });
};
const saveSchedule = () => {
  taskFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      let param = { ...scheduleTaskForm.value };
      param.startDateStr=param.startDate;
      param.endDateStr=param.endDate;

      param.isAllowMail =
        scheduleTaskForm.value.noticetyes.findIndex((x: string) => x == "mail") != -1
          ? true
          : false;
      param.isAllowSms =
        scheduleTaskForm.value.noticetyes.findIndex((x: string) => x == "sms") != -1
          ? true
          : false;
      param.isAllowSignarl =
        scheduleTaskForm.value.noticetyes.findIndex((x: string) => x == "signalr") != -1
          ? true
          : false;

      let keeperInfo = [];

      for (let i of scheduleTaskForm.value.keeperInfo) {
        let x = userlist.value.find((x: any) => x.id == i);
        if (x != null) {
          keeperInfo.push({
            userId: x.id,
            userName: x.surname,
            mailAddress: x.email,
            phoneNumber: x.phoneNumber,
            weChatId: "",
          });
        }
      }
      param.keeperInfo = keeperInfo;

      if (isEdit.value == false) {
        addscheduletask(param).then((res) => {
          ElNotification({
            title: "提示",
            message: "添加成功",
            type: "success",
            duration: 2000,
          });
          closeDialog();
          emit("refresh");
        });
      } else {
      }
    }
  });
};
watch(
  () => scheduleTaskForm.value.runLoop,
  (newVal) => {
    if (newVal) {
      rules.value.cronExpression = [
        { required: true, message: "请输入Cron表达式", trigger: "blur" },
      ];
    } else {
      delete rules.value["cronExpression"];
    }
    taskFormRef.value?.validate();
  }
);
watch(
  () => scheduleTaskForm.value.jobType,
  (newVal) => {
    if (newVal == 1) {
      rules.value.httpRequestUrl = [
        { required: true, message: "请输入请求地址", trigger: "blur" },
      ];
      rules.value.httpMethod = [
        { required: true, message: "请选择请求方式", trigger: "change" },
      ];
    } else {
      delete rules.value["httpRequestUrl"];
      delete rules.value["httpMethod"];
      taskFormRef.value?.clearValidate("httpRequestUrl");
      taskFormRef.value?.clearValidate("httpMethod");

      rules.value.assemblyName = [
        { required: true, message: "请输入程序集名称", trigger: "blur" },
      ];
      rules.value.className = [
        { required: true, message: "请输入执行类名称", trigger: "blur" },
      ];
      rules.value.methodName = [
        { required: true, message: "请输入执行方法名称", trigger: "blur" },
      ];
    }

    //taskForm.value?.validate();
  }
);

const pg_init = () => {
  if (props.scheduleId == null) {
    title.value = "添加任务";
    isEdit.value = false;
  } else {
    title.value = "修改任务";
    isEdit.value = true;
  }
};

onMounted(() => {
  getUser();
  pg_init();
});
</script>
<style lang="scss" scoped>
.el-tabs--card {
  height: 500px;
  /* overflow-y: auto; */
}
.el-tab-pane {
  height: 500px;
  overflow-y: auto;
}
</style>
